import {
    Decoration,
    ViewPlugin,
    MatchDecorator,
    EditorView,
    WidgetType,
} from "@codemirror/view";

class ConditionalOperatorWidget extends WidgetType {
    constructor(name) {
        super();
        this.name = name;
    }

    eq(other) {
        return this.name == other.name;
    }

    toDOM() {
        let element = document.createElement("span");
        element.style.cssText = `
            font-size: 14px;
            color: #1d9271;
    `;
        element.textContent = this.name;
        return element;
    }

    ignoreEvent() {
        return false;
    }
}

const conditionalOperatorMatcher = new MatchDecorator({
    regexp: /如果|那么|否则/g,
    decoration: (match) => {
        return Decoration.replace({
            widget: new ConditionalOperatorWidget(match[0]),
        });
    },
});

export const conditionalOperatorPlugin = ViewPlugin.fromClass(
    class {
        conditionalOperators;

        constructor(view) {
            this.conditionalOperators = conditionalOperatorMatcher.createDeco(view);
        }

        update(update) {
            this.conditionalOperators = conditionalOperatorMatcher.updateDeco(
                update,
                this.conditionalOperators
            );
        }
    },
    {
        decorations: (instance) => instance.conditionalOperators,
        provide: (plugin) =>
            EditorView.atomicRanges.of((view) => {
                return view.plugin(plugin)?.conditionalOperators || Decoration.none;
            }),
    }
);
